package com.xiaoxiao.springbootstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxiao.springbootstudy.pojo.User;
import com.xiaoxiao.springbootstudy.pojo.vo.CountResult;
import com.xiaoxiao.springbootstudy.service.UserRoleService;
import com.xiaoxiao.springbootstudy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @GetMapping("/listUsers")
    public Map<String, Object> getUsers(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        return userService.getUserRolerService(pageNum, pageSize);
    }

    @PostMapping("/addUser")
    public Map<String, Object> addUser(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "添加失败");
        try {
            userService.saveUserRolerService(user);
            result.put("code", 200);
            result.put("msg", "添加用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @GetMapping("/queryUserRids/{id}")
    public List<Integer> queryUserRids(@PathVariable Integer id) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", id); //where uid=?
        wrapper.select("rid");
        List<Integer> list = userRoleService.listObjs(wrapper);
        return list;

    }

    @PostMapping("/updateUser")
    public Map<String, Object> updateUser(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "操作失败");
        try {
            userService.updateUserRoleService(user);
            result.put("code", 200);
            result.put("msg", "更新用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    @GetMapping("/delUser/{id}")
    public Map<String,Object> delUser(@PathVariable Integer id){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败");
        try{
            userService.deleteUserRoleService(id);
            result.put("code",200);
            result.put("msg","删除用户成功");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    @GetMapping("/countEmpAge")
    public List<CountResult> countEmpAge(){
        return userService.countEmployeeAageService();
    }

    @GetMapping("/countEmpEdu")
    public List<CountResult> countEmpEdu() {
        return userService.countEmployeeEduService();
    }
}
